package com.example.webviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class WebPageFragment extends Fragment {

    private Activity mActivity;
    private WebView mWebView = null;
    private String mUrl;
    private Controller mController;

    private WebViewStateChangeListener mWebViewStateChangeListener = null;

    @Override
    public void setArguments(Bundle bundle) {
        super.setArguments(bundle);

        if (bundle != null) {
            mUrl = bundle
                    .getString(WebViewExampleConstant.EXTRA_VIEW_SOURCE_URL);
        }
    }

    public void setWebViewStateChangeListener(
            WebViewStateChangeListener listener) {
        mWebViewStateChangeListener = listener;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.view_source_web_page, container,
                false);
        if (view != null) {
            mWebView = (WebView) view.findViewById(R.id.webview);
            if (mWebViewStateChangeListener != null) {
                mWebViewStateChangeListener.onWebViewCreate();
            }

            mController = new Controller(mWebView);

            if (mWebViewStateChangeListener != null) {
                mWebViewStateChangeListener
                        .onWebViewControllerCreated(mController);
            }
        }

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mUrl != null && mController != null) {
            mController.loadUrl(mUrl);
        }
    }
}
